package net.ibizsys.eclipse.studio.tree;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.jface.viewers.ILazyTreeContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;

/**
 * 懒加载树数据提供对象
 * 
 * @author <a href='http://www.weibo.com/xjtoo' target='_blank'>Enmaai</a>
 */
public abstract class IBizLazyTreeContentProvider implements ILazyTreeContentProvider
{
	private TreeViewer viewer;
	private List<IBizTreeNode> roots = new ArrayList<IBizTreeNode>();

	public IBizLazyTreeContentProvider(TreeViewer viewer)
	{
		this.viewer = viewer;
	}

	@Override
	@SuppressWarnings("unchecked")
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput)
	{
		roots = (List<IBizTreeNode>) newInput;
	}

	@Override
	public void dispose()
	{
	}

	@Override
	public Object getParent(Object element)
	{
		if (element instanceof IBizTreeNode)
		{
			IBizTreeNode node = (IBizTreeNode) element;

			if (!node.isRootNode())
			{
				return node.getParent();
			}
		}

		return roots;
	}

	@Override
	public void updateChildCount(Object element, int currentChildCount)
	{
		if (element == roots)
		{
			viewer.setChildCount(element, roots.size());
		} else
		{
			onUpdateChildCount((IBizTreeNode) element);
		}
	}

	@Override
	public void updateElement(Object parent, int index)
	{
		Object element;
		if (parent instanceof IBizTreeNode)
		{
			element = ((IBizTreeNode) parent).getChildren().get(index);
		} else
		{
			element = roots.get(index);
		}

		viewer.replace(parent, index, element);
		updateChildCount(element, -1);
	}

	/**
	 * 刷新子节点数量
	 * 
	 * @param treeNode
	 */
	protected abstract void onUpdateChildCount(IBizTreeNode treeNode);
}
